package com.subject.shuati.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.subject.shuati.common.entity.PageResult;
import com.subject.shuati.common.enums.IsDeleteFlagEnum;
import com.subject.shuati.common.util.IdWorkerUtil;
import com.subject.shuati.common.util.LoginUtil;
import com.subject.shuati.domain.covert.SubjectInfoConverter;
import com.subject.shuati.domain.entity.SubjectInfoBo;
import com.subject.shuati.domain.entity.SubjectOptionBo;
import com.subject.shuati.domain.handler.subject.SubjectTypeHandler;
import com.subject.shuati.domain.handler.subject.SubjectTypeHandlerFactory;
import com.subject.shuati.domain.redis.RedisUtil;
import com.subject.shuati.domain.service.SubjectInfoDomainService;
import com.subject.shuati.domain.service.SubjectLikedDomainService;
import com.subject.shuati.infra.basic.entity.SubjectInfo;
import com.subject.shuati.infra.basic.entity.SubjectInfoEs;
import com.subject.shuati.infra.basic.entity.SubjectLabel;
import com.subject.shuati.infra.basic.entity.SubjectMapping;
import com.subject.shuati.infra.basic.service.SubjectEsService;
import com.subject.shuati.infra.basic.service.SubjectInfoService;
import com.subject.shuati.infra.basic.service.SubjectLabelService;
import com.subject.shuati.infra.basic.service.SubjectMappingService;
import com.subject.shuati.infra.entity.UserInfo;
import com.subject.shuati.infra.rpc.UserRpc;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.joda.time.DateTime;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;
    @Resource
    private UserRpc userRpc;
    @Resource
    private RedisUtil redisUtil;
    private static final String RANK_KEY = "subject_rank";
    @Override
    public void add(SubjectInfoBo subjectInfoBo) {
        if (log.isInfoEnabled()){
            log.info("SubjectLabelBoController.add.Bo:{}", JSON.toJSONString(subjectInfoBo));
        }
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.BoConverterToInfo(subjectInfoBo);
        subjectInfo.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.getCode());
        subjectInfoService.insert(subjectInfo);
        SubjectTypeHandler subjectTypeHandler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBo.setId(subjectInfo.getId());
        subjectTypeHandler.add(subjectInfoBo);
        List<Integer> categoryIds = subjectInfoBo.getCategoryIds();
        List<Integer> labelIds = subjectInfoBo.getLabelIds();
        List<SubjectMapping> mappingList = new ArrayList<>();
        categoryIds.forEach(categoryId->{
            labelIds.forEach(labelId->{
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.getCode());
                mappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(mappingList);
        //同步到Es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBo.getSubjectAnswer());
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectInfoEs.setCreateUser("管理员");
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectEsService.insert(subjectInfoEs);
        //使用redisZadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);
    }

    /**
     * 分页查询题目列表
     * @param subjectInfoBo
     * @return
     */
    @Override
    public PageResult<SubjectInfoBo> getSubjectPage(SubjectInfoBo subjectInfoBo) {
        PageResult<SubjectInfoBo> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBo.getPageNo());
        pageResult.setPageSize(subjectInfoBo.getPageSize());
        int start = (subjectInfoBo.getPageNo() - 1) * subjectInfoBo.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.BoConverterToInfo(subjectInfoBo);
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBo.getCategoryId()
                , subjectInfoBo.getLabelId());
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBo.getCategoryId()
                , subjectInfoBo.getLabelId(), start, subjectInfoBo.getPageSize());
        List<SubjectInfoBo> subjectInfoBOS = SubjectInfoConverter.INSTANCE.BoConverterToInfoList(subjectInfoList);
        subjectInfoBOS.forEach(info -> {
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setSubjectId(info.getId());
            List<SubjectMapping> mappingList = subjectMappingService.queryLabelByCategoryId(subjectMapping);
            List<Long> labelIds = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> labelList = subjectLabelService.queryBatchByLabelIds(labelIds);
            List<String> labelNames = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
            info.setLabelName(labelNames);
        });
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoBo querySubjectInfo(SubjectInfoBo subjectInfoBo) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBo.getId());
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBo optionBO = handler.query(subjectInfo.getId().intValue());
        SubjectInfoBo bo = SubjectInfoConverter.INSTANCE.OptionConverterToBo(optionBO, subjectInfo);
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.getCode());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelByCategoryId(subjectMapping);
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.queryBatchByLabelIds(labelIdList);
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelName(labelNameList);
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBo.getId().toString(), LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBo.getId().toString()));
        assembleSubjectCursor(subjectInfoBo, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBo subjectInfoBo, SubjectInfoBo bo) {
        Long subjectId = subjectInfoBo.getId();
        Long categoryId = subjectInfoBo.getCategoryId();
        Long labelId = subjectInfoBo.getLabelId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        bo.setLastSubjectId(lastSubjectId);
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBo subjectInfoBo) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setKeyWord(subjectInfoBo.getKeyWord());
        subjectInfoEs.setPageNo(subjectInfoBo.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBo.getPageSize());
        return subjectEsService.searchSubjectInfoList(subjectInfoEs);
    }

    @Override
    public List<SubjectInfoBo> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()){
            log.info("redis获取排行榜数据:{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)){
            return Collections.emptyList();
        }
        List<SubjectInfoBo> boList = new LinkedList<>();
        typedTuples.forEach(rank -> {
            SubjectInfoBo subjectInfoBo = new SubjectInfoBo();
            subjectInfoBo.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBo.setCreateUser(userInfo.getNickName());
            subjectInfoBo.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBo);
        });
        return boList;
    }
}
